package com.demo8.common.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.demo8.basic.annotation.RateLimiter;
import com.demo8.basic.constant.CacheConstants;
import com.demo8.basic.constant.Constants;
import com.demo8.basic.enums.CaptchaEnum;
import com.demo8.basic.enums.LimitType;
import com.demo8.basic.utils.RedisCacheUtils;
import com.demo8.common.domain.CaptchaBodyVO;
import com.demo8.common.service.ICaptchaStrategyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service("image")
public class ImageCaptchaStrategyServiceImpl implements ICaptchaStrategyService {

    @Autowired
    RedisCacheUtils redisCacheUtils;

    @RateLimiter(key = CacheConstants.RATE_LIMIT_KEY + "image:", time = 60, count = 5, limitType = LimitType.IP)
    @Override
    public CaptchaBodyVO generateCaptcha(String target) {
        CaptchaBodyVO res = new CaptchaBodyVO();

        //保存验证码的缓存信息，用于后续登录验证
        String uuid = IdUtil.fastSimpleUUID();
        res.setUuid(uuid);
        //生成验证码信息，并保存
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        System.out.println(">>>>>>>>验证码：" + lineCaptcha.getCode());
        String imageBase64 = lineCaptcha.getImageBase64Data();
        res.setCaptchaCode(imageBase64);
        redisCacheUtils.setCacheObject(CacheConstants.CAPTCHA_CODE_KEY + uuid, lineCaptcha.getCode(), Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        res.setCaptchaType(CaptchaEnum.IMAGE.getType());
        return res;
    }

    @Override
    public CaptchaEnum getType() {

        return CaptchaEnum.IMAGE;
    }
}
